import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../services/coin_purchase_service.dart';

// 金币余额Provider
final coinBalanceProvider = StateNotifierProvider<CoinBalanceNotifier, int>((ref) {
  return CoinBalanceNotifier();
});

class CoinBalanceNotifier extends StateNotifier<int> {
  CoinBalanceNotifier() : super(0) {
    _loadBalance();
  }

  final CoinPurchaseService _purchaseService = CoinPurchaseService();

  Future<void> _loadBalance() async {
    final balance = await _purchaseService.getUserCoins();
    state = balance;
  }

  Future<void> addCoins(int coins) async {
    final currentBalance = await _purchaseService.getUserCoins();
    final newBalance = currentBalance + coins;
    await _purchaseService.setUserCoins(newBalance);
    state = newBalance;
  }

  Future<void> spendCoins(int coins) async {
    final currentBalance = await _purchaseService.getUserCoins();
    if (currentBalance >= coins) {
      final newBalance = currentBalance - coins;
      await _purchaseService.setUserCoins(newBalance);
      state = newBalance;
    } else {
      throw Exception('Insufficient coins');
    }
  }

  Future<void> refreshBalance() async {
    await _loadBalance();
  }
}

// VIP状态Provider
final vipStatusProvider = StateNotifierProvider<VipStatusNotifier, VipStatus>((ref) {
  return VipStatusNotifier();
});

class VipStatus {
  final bool isVip;
  final int remainingDays;
  final DateTime? expiryDate;

  const VipStatus({
    required this.isVip,
    required this.remainingDays,
    this.expiryDate,
  });

  VipStatus copyWith({
    bool? isVip,
    int? remainingDays,
    DateTime? expiryDate,
  }) {
    return VipStatus(
      isVip: isVip ?? this.isVip,
      remainingDays: remainingDays ?? this.remainingDays,
      expiryDate: expiryDate ?? this.expiryDate,
    );
  }
}

class VipStatusNotifier extends StateNotifier<VipStatus> {
  VipStatusNotifier() : super(const VipStatus(isVip: false, remainingDays: 0)) {
    _loadVipStatus();
  }

  final CoinPurchaseService _purchaseService = CoinPurchaseService();

  Future<void> _loadVipStatus() async {
    final prefs = await SharedPreferences.getInstance();
    final expiryTimestamp = prefs.getInt('vip_expiry_timestamp');
    
    if (expiryTimestamp != null) {
      // 检查是否为终身VIP
      if (expiryTimestamp == -1) {
        state = const VipStatus(
          isVip: true,
          remainingDays: -1, // -1 表示永久
          expiryDate: null,
        );
        return;
      }
      
      final expiryDate = DateTime.fromMillisecondsSinceEpoch(expiryTimestamp);
      final now = DateTime.now();
      
      if (expiryDate.isAfter(now)) {
        final remainingDays = expiryDate.difference(now).inDays + 1;
        state = VipStatus(
          isVip: true,
          remainingDays: remainingDays,
          expiryDate: expiryDate,
        );
      } else {
        // VIP已过期
        await prefs.remove('vip_expiry_timestamp');
        state = const VipStatus(isVip: false, remainingDays: 0);
      }
    } else {
      state = const VipStatus(isVip: false, remainingDays: 0);
    }
  }

  Future<void> activateVip(int days) async {
    final prefs = await SharedPreferences.getInstance();
    final now = DateTime.now();
    
    // 获取当前过期时间
    final currentExpiryTimestamp = prefs.getInt('vip_expiry_timestamp');
    DateTime newExpiryDate;
    
    if (currentExpiryTimestamp != null) {
      // 如果已经是终身VIP，保持终身状态，不降级
      if (currentExpiryTimestamp == -1) {
        // 已经是终身VIP，无需更改
        return;
      }
      
      final currentExpiryDate = DateTime.fromMillisecondsSinceEpoch(currentExpiryTimestamp);
      if (currentExpiryDate.isAfter(now)) {
        // VIP还未过期，在现有基础上累加
        newExpiryDate = currentExpiryDate.add(Duration(days: days));
      } else {
        // VIP已过期，从现在开始计算
        newExpiryDate = now.add(Duration(days: days));
      }
    } else {
      // 首次开通VIP
      newExpiryDate = now.add(Duration(days: days));
    }
    
    // 保存新的过期时间
    await prefs.setInt('vip_expiry_timestamp', newExpiryDate.millisecondsSinceEpoch);
    
    // 更新状态
    final remainingDays = newExpiryDate.difference(now).inDays + 1;
    state = VipStatus(
      isVip: true,
      remainingDays: remainingDays,
      expiryDate: newExpiryDate,
    );
  }

  Future<void> activateLifetimeVip() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt('vip_expiry_timestamp', -1); // -1 表示永久
    
    state = const VipStatus(
      isVip: true,
      remainingDays: -1, // -1 表示永久
      expiryDate: null,
    );
  }

  Future<void> refreshStatus() async {
    await _loadVipStatus();
  }
}